package com.sw.bbs.board.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sw.bbs.board.dao.user.UserBoardMapper;
import com.sw.bbs.board.pojo.user.UserBoard;
import com.sw.bbs.board.vo.request.board.InsertBoardRequest;
import com.sw.bbs.board.vo.request.board.QueryBoardRequest;
import com.sw.bbs.board.vo.request.board.UpdateBoardRequest;
import com.sw.bbs.board.vo.response.board.BoardDetailResponse;
import com.sw.bbs.board.vo.response.board.BoardTreeResponse;
import com.sw.bbs.common.common.ErrorCode;
import com.sw.bbs.common.common.ServiceException;
import com.sw.bbs.board.dao.BoardMapper;
import com.sw.bbs.board.pojo.Board;
import com.sw.bbs.user.pojo.User;
import com.sw.bbs.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sw.bbs.board.service.BoardService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Desc: No Desc
 * @Author: wusonghe
 * @Date: 2019/3/4 16:08
 */
@Service
public class BoardServiceImpl implements BoardService {

    private static final Logger logger = LoggerFactory.getLogger(BoardServiceImpl.class);

    @Autowired
    private BoardMapper boardMapper;

    @Autowired
    private UserBoardMapper userboardMapper;

    @Autowired
    private UserService authService;

    @Override
    public List<BoardTreeResponse> queryboardTree() throws ServiceException{

        List<BoardTreeResponse> treeResponseList = new ArrayList<>();

        QueryBoardRequest queryBoardRequest = new QueryBoardRequest();
        queryBoardRequest.setLevel(0);
        List<Board> boards = boardMapper.queryQueryListResponse(queryBoardRequest);
        for (Board board :boards) {
            BoardTreeResponse treeResponse = new BoardTreeResponse();
            BeanUtils.copyProperties(board,treeResponse);
            QueryBoardRequest childQuery = new QueryBoardRequest();
            childQuery.setParentBoardId(board.getBoardId());
            List<Board> childBoards = boardMapper.queryQueryListResponse(childQuery);
            childBoards = childBoards.stream().map(b->{
                b.setUpdateTime(null);
                b.setCreateTime(null);
                return b;
            }).collect(Collectors.toList());
            treeResponse.setChildBoards(childBoards);
            treeResponseList.add(treeResponse);
        }
        return treeResponseList;
    }

    @Override
    public PageInfo<Board> queryboardList(QueryBoardRequest request) {

//        StringUtils.isNumeric()

        PageHelper.startPage(request.getOffset(),request.getLimit());
        List<Board> boardes = boardMapper.queryQueryListResponse(request);
        return PageInfo.of(boardes);
    }

    @Override
    public BoardDetailResponse queryboardDetail(Integer boardId) {
        Board board = boardMapper.selectByPrimaryKey(boardId);
        BoardDetailResponse detailResponse = new BoardDetailResponse();
        BeanUtils.copyProperties(board,detailResponse);
        return detailResponse;
    }

    @Override
    @Transactional
    public Integer insertboardByRequest(InsertBoardRequest insertboardRequest,
                                        HttpServletRequest httpServletRequest) throws ServiceException {

        try {
            User user = authService.getUserByRequest(httpServletRequest);
            if (user!=null) {
                Board board = new Board();
                BeanUtils.copyProperties(insertboardRequest,board);
                boardMapper.insertSelective(board);
                UserBoard userboard = new UserBoard();
                userboard.setUserId(user.getUserId());
                userboard.setBoardId(board.getBoardId());
                return userboardMapper.insertSelective(userboard);
            }
            return 0;

        }catch (Exception e) {
            logger.error("insert board fail");
            throw new ServiceException(ErrorCode.BUSINESS_SERVER_ERROR, "insert board fail");

        }
    }

    /**
     * 更新
     *
     * @param updateboardRequest
     * @param httpServletRequest
     * @return
     * @throws ServiceException
     */
    @Override
    public Integer updateboardByRequest(UpdateBoardRequest updateboardRequest, HttpServletRequest httpServletRequest) throws ServiceException {

        try {
            Board board = new Board();
            BeanUtils.copyProperties(updateboardRequest,board);
            return boardMapper.updateByPrimaryKeySelective(board);
        }catch (Exception e) {
            logger.error("update board fail");
            throw new ServiceException(ErrorCode.BUSINESS_SERVER_ERROR,"update board fail");
        }

    }

    /**
     * 删除
     *
     * @param boardId
     * @return
     * @throws ServiceException
     */
    @Override
    public Integer deleteboardByRequest(Integer boardId) throws ServiceException {
        try {
            return boardMapper.deleteByPrimaryKey(boardId);
        }catch (Exception e) {

            logger.error("delete board fail");
            throw new ServiceException(ErrorCode.BUSINESS_SERVER_ERROR,"delete board fail");

        }
    }

    /**
     * 热门板块
     * - 根据收藏量排序
     *
     * @return
     * @throws ServiceException
     */
    @Override
    public List<Board> queryHotlist() throws ServiceException {

        QueryBoardRequest queryBoardRequest = new QueryBoardRequest();
        queryBoardRequest.setSortField("collect_num");
        queryBoardRequest.setOnceQuery(1);
        List<Board> boards = boardMapper.queryQueryListResponse(queryBoardRequest);
        return boards;

    }
}
